package com.hzw.saas.web.app.rss.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzw.saas.api.rss.*;
import com.hzw.saas.api.rss.bo.*;
import com.hzw.saas.api.rss.query.JournalArticleFavQuery;
import com.hzw.saas.api.rss.query.JournalArticleSearchQuery;
import com.hzw.saas.api.rss.query.JournalSubQuery;
import com.hzw.saas.api.user.IUserRightsService;
import com.hzw.saas.api.user.bo.UserRightsBO;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.config.util.PageParam;
import com.hzw.saas.common.config.util.PageUtils;
import com.hzw.saas.common.security.utils.SecurityUtils;
import com.hzw.saas.common.util.MapperUtil;
import com.hzw.saas.common.util.SnowFlakeUtil;
import com.hzw.saas.web.app.rss.dto.*;
import com.hzw.saas.web.app.rss.param.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 期刊站点 前端控制器
 * </p>
 *
 * @author sonam
 * @since 2021-06-30
 */
@Slf4j
@Controller
@RequiredArgsConstructor
@Api(tags = "文献期刊/期刊订阅")
@RequestMapping("/journal/rss")
public class JournalController {

    @Resource(name = "journalArticleService")
    private IJournalArticleService journalArticleService;
    @Resource(name = "journalCatalogService")
    private IJournalCatalogService journalCatalogService;
    @Resource(name = "journalService")
    private IJournalService journalService;
    @Resource(name = "journalUserSubService")
    private IJournalUserSubService journalUserSubService;
    @Resource(name = "rssEsService")
    private IRssEsService rssEsService;
    @Resource(name = "journalUserActionService")
    private IJournalUserActionService actionService;
    @Resource(name = "journalCatalogUserService")
    private IJournalCatalogUserService journalCatalogUserService;
    @Resource(name = "journalUserActionService")
    private IJournalUserActionService journalUserActionService;
    @Resource(name = "journalCustomService")
    private IJournalCustomService journalCustomService;
    @Resource(name = "journalUserAxisService")
    private IJournalUserAxisService journalUserAxisService;
    private final IUserRightsService userRightsService;

    @ApiOperationSort(1)
    @GetMapping("/list")
    @SysLog(operation = "获取站点分类列表")
    @ApiOperation(value = "获取站点分类列表")
    public ResponseEntity<IPage<JournalDTO>> journalRssList(@ApiParam(value = "分类ID集合") @RequestParam(required = false) List<String> catalogIds, PageParam pageParam) {
        IPage<JournalBO> journalBOIPage = journalCustomService.pageByCatalogIds(pageParam, catalogIds,SecurityUtils.getUser().getUserId());
        IPage<JournalDTO> journalDTOIPage = buildJournalRss(journalBOIPage);
        findUnReadNum(journalDTOIPage.getRecords());
        return ResponseEntity.ok(journalDTOIPage);
    }

    @ApiOperationSort(2)
    @GetMapping("/article")
    @SysLog(operation = "获取订阅的文章列表（分页）")
    @ApiOperation(value = "获取订阅的文章列表（分页）")
    public ResponseEntity<IPage<JournalArticleWithRssDto>> journalRssArticleList(PageParam pageParam,
                                                                                 @ApiParam(value = "站点id")@RequestParam(required = false)String journalId) {
        List<JournalUserSubBO> journalUserSubBOS = journalUserSubService.pushSubscribe(SecurityUtils.getUser().getUserId());
        if (CollectionUtil.isEmpty(journalUserSubBOS)){
            return ResponseEntity.ok(new Page<>());
        }
        ArrayList<String> strings = new ArrayList<>();
        if (StrUtil.isNotBlank(journalId)){
            strings.add(journalId);
        }else {
            List<String> rssIds = journalUserSubBOS.stream().map(JournalUserSubBO::getJournalId).collect(Collectors.toList());
            strings.addAll(rssIds);
        }

        List<JournalCustomBO> byIds = journalCustomService.findByIds(strings);
        if (CollectionUtil.isEmpty(byIds)){
            return ResponseEntity.ok(new Page<>());
        }
        List<String> collect = byIds.stream().map(JournalCustomBO::getJournalId).collect(Collectors.toList());
        IPage<JournalArticleBO> journalArticlePage = journalArticleService.findJournalArticlePage(collect, pageParam);

        IPage<JournalArticleWithRssDto> journalArticleWithRssDtoIPage = PageUtils.convert(journalArticlePage, JournalArticleWithRssDto.class);
        List<JournalArticleWithRssDto> journalArticleWithRssDtos = journalArticleWithRssDtoIPage.getRecords();
        journalArticleWithRssDtos.forEach(journalArticleWithRssDto -> {
            // 设置分类
            buildArticleCatalog(journalArticleWithRssDto);
            // 判断该RSS是否收藏
            journalArticleWithRssDto.setIsFav(actionService.journalArticleIsFav(journalArticleWithRssDto.getPid(), SecurityUtils.getUser().getUserId()));
            // 设置期刊信息
            if (StrUtil.isNotBlank(journalArticleWithRssDto.getRssId())){
                JournalBO journalBO = journalService.getById(journalArticleWithRssDto.getRssId());
                journalArticleWithRssDto.setJournalIssn(journalBO.getJournalIssn());
                journalArticleWithRssDto.setJournalName(journalBO.getJournalName());
                journalArticleWithRssDto.setIsRead(0);

            }

        });
        //设置已读未读
        if (CollectionUtil.isNotEmpty(journalArticleWithRssDtos)){
            ArrayList<String> stringArrayList = new ArrayList<>();
            stringArrayList.add(journalId);
            JournalCustomBO byId = journalCustomService.findById(journalId);
            if (byId != null){
                //有且仅可能有一条数据
                Date readTime = byId.getReadTime();
                ArrayList<JournalArticleWithRssDto> journalArticleWithRssDtoArrayList = new ArrayList<>();
                //处理上一次全部已读数据
                journalArticleWithRssDtos.forEach(journalArticleWithRssDto -> {
                    if (journalArticleWithRssDto.getCreateTime().before(readTime)){
                        journalArticleWithRssDto.setIsRead(1);
                    }else {
                        journalArticleWithRssDtoArrayList.add(journalArticleWithRssDto);
                    }
                });
                if (CollectionUtil.isNotEmpty(journalArticleWithRssDtoArrayList)){
                    List<String> pids = journalArticleWithRssDtoArrayList.stream().map(JournalArticleWithRssDto::getPid).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(pids)){
                        List<JournalUserActionBO> byUserAndArticleIds = journalUserActionService.findByUserAndArticleIds(pids, SecurityUtils.getUserId());
                        journalArticleWithRssDtos.forEach(journalArticleWithRssDto -> {
                            byUserAndArticleIds.forEach(journalUserActionBO -> {
                                if (journalArticleWithRssDto.getPid().equals(journalUserActionBO.getArticleId())){
                                    journalArticleWithRssDto.setIsRead(1);
                                }
                            });
                        });
                    }
                }

            }
        }
        journalArticleWithRssDtoIPage.setRecords(journalArticleWithRssDtos);
        return ResponseEntity.ok(journalArticleWithRssDtoIPage);
    }

    /**
     * 设置期刊分类
     * @param journalArticleDTO
     */
    private void buildArticleCatalog(JournalArticleDTO journalArticleDTO) {
        String rssId = journalArticleDTO.getRssId();
        JournalBO journalBO = journalService.getById(rssId);
        if (journalBO != null && StrUtil.isNotBlank(journalBO.getCatalogId())) {
            String catalogId = journalBO.getCatalogId();
            List<JournalCatalogBO> journalCatalogBOS = journalCatalogService.getCatalogByIds(Collections.singletonList(catalogId));
            if (CollectionUtil.isNotEmpty(journalCatalogBOS)) {
                journalArticleDTO.setCatalog(MapperUtil.nf().map(journalCatalogBOS.get(0), JournalCatalogDTO.class));
            }
        }
    }


    @ApiOperationSort(3)
    @PostMapping("/article/list/search")
    @SysLog(operation = "搜索期刊文章（分页）")
    @ApiOperation(value = "搜索期刊文章（分页）")
    public ResponseEntity<IPage<JournalArticleWithRssDto>> searchJournalRssArticleList(@RequestBody JournalArticleSearchParam searchParam) {
        AssertUtil.assertThrow("请传入分页参数",searchParam.getPageParam() == null);
        //解决分类搜索问题
        List<String> catalogIds = searchParam.getCatalogIds();
        if (CollectionUtil.isNotEmpty(catalogIds)){
            List<JournalCatalogUserBO> byIds = journalCatalogUserService.findByIds(catalogIds);
            if (CollectionUtil.isNotEmpty(byIds)){
                List<String> collect = byIds.stream().map(JournalCatalogUserBO::getCatalogId).collect(Collectors.toList());
                searchParam.setCatalogIds(collect);
            }
        }
        JournalArticleSearchQuery searchQuery = MapperUtil.nt().map(searchParam, JournalArticleSearchQuery.class);
        List<JournalArticleNoticeBO> journalArticleNotices = rssEsService.findArticle(searchQuery, searchParam.getPageParam(),SecurityUtils.getUser().getUserId());
        List<JournalArticleWithRssDto> journalArticleWithRssDtos = MapperUtil.nf().mapAsList(journalArticleNotices, JournalArticleWithRssDto.class);
        journalArticleWithRssDtos.forEach(journalArticleWithRssDto -> {
            // 设置作者信息
            List<String> authors = journalArticleWithRssDto.getAuthors();
            if(CollectionUtil.isNotEmpty(authors)) {
                String author = String.join(",", authors);
                journalArticleWithRssDto.setAuthor(author);
            }
            // 设置分类
            String catalogId = journalArticleWithRssDto.getCatalogId();
            List<JournalCatalogBO> journalCatalogBOS = journalCatalogService.getCatalogByIds(Arrays.asList(catalogId));
            if (CollectionUtil.isNotEmpty(journalCatalogBOS)) {
                journalArticleWithRssDto.setCatalog(MapperUtil.nf().map(journalCatalogBOS.get(0), JournalCatalogDTO.class));
            }
            // 设置收藏
            journalArticleWithRssDto.setIsFav(actionService.journalArticleIsFav(journalArticleWithRssDto.getPid(), SecurityUtils.getUser().getUserId()));
        });
        if(CollectionUtil.isNotEmpty(journalArticleWithRssDtos)){
            List<String> articleId = journalArticleWithRssDtos.stream().map(JournalArticleWithRssDto::getPid).collect(Collectors.toList());
            List<JournalArticleBO> journalArticleBOS = journalArticleService.findByIds(articleId);
            if (CollectionUtil.isNotEmpty(journalArticleBOS)){
                journalArticleWithRssDtos.forEach(journalArticleWithRssDto -> {
                    journalArticleBOS.forEach(journalArticleBO -> {
                        if (journalArticleWithRssDto.getPid().equals(journalArticleBO.getPid())){
                            journalArticleWithRssDto.setCreateTime(journalArticleBO.getCreateTime());
                        }
                    });
                });
            }
        }
        Page page = searchParam.getPageParam().convert();
        page.setRecords(journalArticleWithRssDtos);
        return ResponseEntity.ok(page);
    }

    @ApiOperationSort(4)
    @GetMapping("/sub/list")
    @SysLog(operation = "获取我的订阅站点")
    @ApiOperation(value = "获取我的订阅站点")
    public ResponseEntity<IPage<JournalDTO>> mySubJournalList(PageParam pageParam) {
        if (pageParam.getSize() == 0 || pageParam.getCurrent() == 0L){
            pageParam = PageParam.getBigPageParam();
        }
        IPage<JournalBO> mySubscribe = journalService.findMySubscribe(pageParam, SecurityUtils.getUser().getUserId());
        IPage<JournalDTO> journalDTOIPage = buildJournalRss(mySubscribe);
        List<JournalDTO> records = journalDTOIPage.getRecords();
        findUnReadNum(records);
        findParent(records);
        return ResponseEntity.ok(journalDTOIPage);
    }

    private void findParent(List<JournalDTO> records) {
        if (CollectionUtil.isNotEmpty(records)){
            List<String> collect = records.stream().map(JournalDTO::getPid).collect(Collectors.toList());
            List<JournalCustomBO> byIds = journalCustomService.findByIds(collect);
            List<JournalCustomDTO> journalCustomDTOS = MapperUtil.nf().mapAsList(byIds, JournalCustomDTO.class);
            if (CollectionUtil.isNotEmpty(journalCustomDTOS)){
                List<String> catalogs = journalCustomDTOS.stream().map(JournalCustomBO::getCatalogId).collect(Collectors.toList());
                List<JournalCatalogUserBO> journalCatalogUserBOS = journalCatalogUserService.findByIds(catalogs);
                if (CollectionUtil.isNotEmpty(journalCatalogUserBOS)){
                    List<JournalCatalogUserBO> journalCatalogUserBOList = new ArrayList<>();
                    journalCatalogUserBOS.forEach(journalCatalogUserBO -> {
                        if (!journalCatalogUserBO.getParentId().equals("0")||journalCatalogUserBO.getParentId() != null){
                            journalCatalogUserBOList.add(journalCatalogUserBO);
                        }
                    });
                    if (CollectionUtil.isNotEmpty(journalCatalogUserBOList)){
                        List<String> stringList= journalCatalogUserBOList.stream().map(JournalCatalogUserBO::getParentId).collect(Collectors.toList());
                        List<JournalCatalogUserBO> byIds1 = journalCatalogUserService.findByIds(stringList);
                        HashMap<String, String> stringStringHashMap = new HashMap<>();
                        journalCatalogUserBOList.forEach(journalCatalogUserBO -> {
                            byIds1.forEach(journalCatalogUserBO1 -> {
                                if (journalCatalogUserBO.getParentId().equals(journalCatalogUserBO1.getPid())){
                                    stringStringHashMap.put(journalCatalogUserBO.getPid(),journalCatalogUserBO1.getCatalogName());
                                }
                            });
                        });

                        journalCustomDTOS.forEach(journalCustomDTO -> {
                            stringStringHashMap.forEach((s, s2) -> {
                                if (journalCustomDTO.getCatalogId().equals(s)){
                                    journalCustomDTO.setParentName(s2);
                                }
                                journalCatalogUserBOList.forEach(journalCatalogUserBO -> {
                                    if (journalCustomDTO.getCatalogId().equals(journalCatalogUserBO.getPid())){
                                        journalCustomDTO.setCatalogName(journalCatalogUserBO.getCatalogName());
                                    }
                                });
                            });
                        });

                        records.forEach(journalDTO -> {
                            journalCustomDTOS.forEach(journalCustomDTO -> {
                                if (journalDTO.getPid().equals(journalCustomDTO.getPid())){
                                    journalDTO.setParentName(journalCustomDTO.getParentName());
                                    journalDTO.setCatalogName(journalCustomDTO.getCatalogName());
                                }
                            });

                        });
                    }

                }

            }
        }
    }

    private void findUnReadNum( List<JournalDTO> journalDTOS){
        String userId = SecurityUtils.getUserId();
        if(CollectionUtil.isNotEmpty(journalDTOS)){
            journalDTOS.forEach(journalDTO -> {
                journalDTO.setUnReadNum(0);
            });
            HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
            List<String> ids = journalDTOS.stream().map(JournalDTO::getPid).collect(Collectors.toList());
            List<JournalCustomBO> byUserAndRssId = journalCustomService.findByIds(ids);
            if (CollectionUtil.isNotEmpty(byUserAndRssId)){
                List<String> strings = byUserAndRssId.stream().map(JournalCustomBO::getJournalId).collect(Collectors.toList());
                HashMap<String, Date> stringDateHashMap = new HashMap<>();
                byUserAndRssId.forEach(journalCustomBO -> {
                    stringDateHashMap.put(journalCustomBO.getJournalId(),journalCustomBO.getReadTime());
                });
                List<JournalArticleBO> byJournalIds = journalArticleService.findByJournalIds(strings);
                //所有单条的已读数据
                List<JournalUserActionBO> allJournalUserActionByUserId = journalUserActionService.findAllJournalUserActionByUserId(userId);
                if (CollectionUtil.isNotEmpty(byJournalIds)){
                    //去除所有标记全部已读的数据
                    ArrayList<JournalArticleBO> journalArticleBOArrayList = new ArrayList<>();
                    byJournalIds.forEach(journalArticleBO -> {
                        stringDateHashMap.forEach((s, date) -> {
                            if (journalArticleBO.getRssId().equals(s)&&journalArticleBO.getCreateTime().before(date)){
                                journalArticleBOArrayList.add(journalArticleBO);
                            }
                        });
                    });
                    if(CollectionUtil.isNotEmpty(allJournalUserActionByUserId)){
                        List<String> articles = allJournalUserActionByUserId.stream().map(JournalUserActionBO::getArticleId).collect(Collectors.toList());
                        byJournalIds.forEach(journalArticleBO -> {
                            articles.forEach(s -> {
                                if (journalArticleBO.getPid().equals(s)){
                                    journalArticleBOArrayList.add(journalArticleBO);
                                }
                            });
                        });
                    }
                    byJournalIds.removeAll(journalArticleBOArrayList);
                    if (CollectionUtil.isNotEmpty(byJournalIds)){
                        HashMap<String, Integer> integerHashMap = new HashMap<>();
                        Map<String, List<JournalArticleBO>> collect = byJournalIds.stream().collect(Collectors.groupingBy(JournalArticleBO::getRssId));
                        collect.forEach((s, journalArticleBOS) -> {
                            if (CollectionUtil.isNotEmpty(journalArticleBOS)){
                                integerHashMap.put(s,journalArticleBOS.size());
                            }else {
                                integerHashMap.put(s,0);
                            }
                        });
                        byUserAndRssId.forEach(journalCustomBO -> {
                            integerHashMap.forEach((s, integer) -> {
                                if (journalCustomBO.getJournalId().equals(s)){
                                    stringIntegerHashMap.put(journalCustomBO.getPid(),integer);
                                }
                            });
                        });
                    }
                }
            }
            journalDTOS.forEach(journalDTO -> {
                stringIntegerHashMap.forEach((s, integer) -> {
                    if (journalDTO.getPid().equals(s)){
                        journalDTO.setUnReadNum(integer);
                    }
                });
            });
        }
    }

    private IPage<JournalDTO> buildJournalRss(IPage<JournalBO> journalBOIPage) {
        IPage<JournalDTO> journalDTOIPage = PageUtils.convert(journalBOIPage, JournalDTO.class);
        List<JournalDTO> pageRecords = journalDTOIPage.getRecords();
        List<String> collect = pageRecords.stream().map(JournalDTO::getPid).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(collect)) {
//            Map<String, Integer> unRead = journalUserActionService.findUnRead(collect, SecurityUtils.getUser().getUserId());
            List<String> alreadySub = journalUserSubService.findAlreadySub(collect, SecurityUtils.getUser().getUserId());
            pageRecords.forEach(journalDTO -> {
                alreadySub.forEach(s ->{
                if (journalDTO.getPid().equals(s)){
                    journalDTO.setIsSub(1);
                }
                } );
            });
            pageRecords.forEach(journalDTO -> {
                String pid = journalDTO.getPid();
                if (StrUtil.isNotBlank(pid)){
                    JournalCustomBO byId = journalCustomService.findById(pid);
                    if (byId != null){
                        journalDTO.setCatalogId(byId.getCatalogId());
                        journalDTO.setCatalogName(byId.getJournalName());
                    }
                }
                List<JournalUserSubBO> journalUserSubBOS = journalUserSubService.query(new JournalUserSubBO().setUserId(SecurityUtils.getUser().getUserId()).setJournalId(journalDTO.getPid()));
                if (CollectionUtil.isEmpty(journalUserSubBOS)) {
                    journalDTO.setIsSub(0); // 没有收藏
                } else {
                    journalDTO.setIsSub(1); // 收藏
                }
            });
        }
        return journalDTOIPage;
    }

    @ApiOperationSort(5)
    @GetMapping("/article/fav/list")
    @SysLog(operation = "获取我的收藏文章")
    @ApiOperation(value = "获取我的收藏文章")
    public ResponseEntity<IPage<JournalArticleDTO>> myFavJournalArticleList(PageParam pageParam) {
        IPage<JournalArticleBO> collectionArticles = journalArticleService.findMyCollection(pageParam, SecurityUtils.getUser().getUserId());
        IPage<JournalArticleDTO> collectionArticlePage = PageUtils.convert(collectionArticles, JournalArticleDTO.class);
        List<JournalArticleDTO> journalArticleDTOS = collectionArticlePage.getRecords();
        if (CollectionUtil.isNotEmpty(journalArticleDTOS)){
            journalArticleDTOS.forEach(journalArticleDTO -> {
                // 设置收藏
                journalArticleDTO.setIsFav(1);
                // 设置分类
                buildArticleCatalog(journalArticleDTO);
            });
            List<String> collect = journalArticleDTOS.stream().map(JournalArticleDTO::getRssId).collect(Collectors.toList());
            List<JournalBO> byIds = journalService.findByIds(collect);
            if (CollectionUtil.isNotEmpty(byIds)){
                byIds.forEach(journalBO -> {
                    journalArticleDTOS.forEach(journalArticleDTO -> {
                        if (journalBO.getPid().equals(journalArticleDTO.getRssId())){
                            journalArticleDTO.setJournalIssn(journalBO.getJournalIssn());
                            journalArticleDTO.setJournalName(journalBO.getJournalName());
                        }
                    });
                });
            }
        }
        return ResponseEntity.ok(collectionArticlePage);
    }

    @ApiOperationSort(6)
    @PostMapping("/sub")
    @SysLog(operation = "订阅/取消订阅站点")
    @ApiOperation(value = "订阅/取消订阅站点")
    public ResponseEntity<Boolean> doSub(@RequestBody @Validated JournalSubParam journalSubParam) {
        JournalSubQuery journalSubQuery = MapperUtil.nf().map(journalSubParam, JournalSubQuery.class);
        journalSubQuery.setUserId(SecurityUtils.getUser().getUserId());
        journalService.subJournalRss(journalSubQuery);

        //订阅站点，时间轴开启事件
        if (journalSubParam.getSub() == 1){
            journalUserAxisService.addRecord(SecurityUtils.getUser().getUserId(),journalSubParam.getRssId());
        }
        //取消订阅,时间轴关闭事件
        if (journalSubParam.getSub() == 0){
            ArrayList<String> strings = new ArrayList<>();
            strings.add(journalSubParam.getRssId());
            List<JournalUserAxisBO> ifRead = journalUserAxisService.findIfRead(SecurityUtils.getUser().getUserId(), strings);
            if (CollectionUtil.isNotEmpty(ifRead)){
                List<String> collect = ifRead.stream().filter(o->o.getAxisStatus().equals(0)).map(JournalUserAxisBO::getPid).collect(Collectors.toList());
                journalUserAxisService.updateRecord(collect,1);
            }

        }

        return ResponseEntity.ok(true);
    }

    @ApiOperationSort(7)
    @PostMapping("/article/fav")
    @SysLog(operation = "收藏/取消收藏文章")
    @ApiOperation(value = "收藏/取消收藏文章")
    public ResponseEntity<Boolean> doFav(@RequestBody @Validated JournalArticleFavParam journalArticleFavParam) {
        JournalArticleFavQuery journalArticleFavQuery = MapperUtil.nf().map(journalArticleFavParam, JournalArticleFavQuery.class);
        journalArticleFavQuery.setUserId(SecurityUtils.getUser().getUserId());
        journalArticleService.collectArticle(journalArticleFavQuery);
        return ResponseEntity.ok(true);
    }

    public  void  makeSureUserRights(String userId){
        UserRightsBO userRightsByUser = userRightsService.getUserRightsByUser(userId);
        AssertUtil.assertThrow("用户权限等级不够",userRightsByUser == null || userRightsByUser.getLevelId().equals("1"));
    }
    @ApiOperationSort(8)
    @GetMapping("/catalog")
    @SysLog(operation = "查询当前登陆用户的分类树")
    @ApiOperation(value = "查询当前登陆用户的分类树")
    public ResponseEntity<List<JournalCatalogDTO>>  findJournalCatalogTree(){
        // 获取全部分类
        List<JournalCatalogBO> journalCatalogTree = journalCatalogService.getCatalogByUserId(SecurityUtils.getUser().getUserId());
        List<JournalCatalogBO> journalCatalogTree1 = journalCatalogService.getCatalogByUserId(SecurityUtils.getUser().getUserId());
        List<JournalCatalogDTO> journalCatalogDTOS = MapperUtil.nf().mapAsList(journalCatalogTree1, JournalCatalogDTO.class);
        return ResponseEntity.ok(journalCatalogDTOS);
    }


    @Deprecated
    @ApiOperationSort(10)
    @GetMapping("/parseJob")
    @SysLog(operation = "解析站点RSS并入库")
    @ApiOperation(value = "解析站点RSS并入库")
    public ResponseEntity<Void>  parseJob(){
        journalService.parseJob("");
        return ResponseEntity.ok().build();
    }

    @Deprecated
    @ApiOperationSort(11)
    @GetMapping("/refreshES")
    @SysLog(operation = "es数据同步")
    @ApiOperation(value = "es数据同步")
    public ResponseEntity<Void>  refreshES(){
        journalService.refreshES();
        return ResponseEntity.ok().build();
    }


    @ApiOperationSort(12)
    @GetMapping("/recoveryCatalogUser")
    @SysLog(operation = "一键恢复分类")
    @ApiOperation(value = "一键恢复分类")
    public ResponseEntity<Void>  recoveryCatalogUser(){
        makeSureUserRights(SecurityUtils.getUser().getUserId());
        journalCatalogUserService.recoveryCatalogUser(SecurityUtils.getUser().getUserId());
        return ResponseEntity.ok().build();
    }

    @ApiOperationSort(13)
    @GetMapping("/moveCatalogHeadNode/{headId}/{newParent}")
    @SysLog(operation = "分类拖拽")
    @ApiOperation(value = "分类拖拽")
    public ResponseEntity<Void>  moveCatalogHeadNode(@PathVariable("headId") String headId,
                                                     @PathVariable("newParent") String newParent){
        makeSureUserRights(SecurityUtils.getUser().getUserId());
        journalCatalogService.moveCatalogHeadNode(headId,newParent,SecurityUtils.getUser().getUserId());
        return ResponseEntity.ok().build();
    }

    @ApiOperationSort(14)
    @PostMapping("/addCatalogUser")
    @SysLog(operation = "分类新增")
    @ApiOperation(value = "分类新增")
    public ResponseEntity<Void>  addCatalogUser(@RequestBody @Valid JournalCatalogParam journalCatalogParam){
        makeSureUserRights(SecurityUtils.getUser().getUserId());
        JournalCatalogBO journalCatalogBO = MapperUtil.nf().map(journalCatalogParam, JournalCatalogBO.class);
        ArrayList<JournalCatalogBO> journalCatalogBOS = new ArrayList<>();
        journalCatalogBOS.add(journalCatalogBO);
        journalCatalogService.saveBatch(journalCatalogBOS,SecurityUtils.getUser().getUserId());
        return ResponseEntity.ok().build();
    }

    @ApiOperationSort(15)
    @DeleteMapping("/deleteJournalCatalog/{headId}")
    @SysLog(operation = "删除分类树")
    @ApiOperation(value = "删除分类树")
    public ResponseEntity<Void>  deleteJournalCatalog(@PathVariable("headId") String headId){
        makeSureUserRights(SecurityUtils.getUser().getUserId());
        //查询分类下的站点id
        JournalCatalogUserBO byId = journalCatalogUserService.findById(headId);
        if (byId != null){
            ArrayList<String> strings = new ArrayList<>();   //需要被删除的站点的分类id
            //第一级
            if (byId.getParentId().equals("0") || byId.getParentId() == null){
                List<JournalCatalogUserBO> byParent = journalCatalogUserService.findByParent(byId.getPid());
                if (CollectionUtil.isNotEmpty(byParent)){
                    List<String> collect = byParent.stream().map(JournalCatalogUserBO::getPid).collect(Collectors.toList());
                    strings.addAll(collect);
                }
            }else {
                strings.add(byId.getPid());
            }
            if (CollectionUtil.isNotEmpty(strings)){
                List<JournalCustomBO> byCatalogIds = journalCustomService.findByCatalogIds(strings);
                if (CollectionUtil.isNotEmpty(byCatalogIds)){
                    List<String> collect = byCatalogIds.stream().map(JournalCustomBO::getPid).collect(Collectors.toList());
                    collect.forEach(s -> {
                        deleteById(s);
                    });
                }
            }

        }

        //删除站点
        journalCatalogService.deleteJournalCatalogBO(headId,SecurityUtils.getUser().getUserId());
        return ResponseEntity.ok().build();
    }


    @ApiOperationSort(17)
    @GetMapping("/changeReadStatus/{articleId}")
    @SysLog(operation = "修改阅读状态")
    @ApiOperation(value = "修改阅读状态")
    public ResponseEntity<Void>  changeReadStatus(@PathVariable("articleId")String articleId){
        journalUserActionService.changeReadStatus( articleId,SecurityUtils.getUser().getUserId());
        return ResponseEntity.ok().build();
    }

    @ApiOperationSort(22)
    @GetMapping("/moveCustom/{pid}/{newCatalogId}")
    @SysLog(operation = "站点移动")
    @ApiOperation(value = "站点移动")
    public ResponseEntity<Void>  moveCustom(@PathVariable("pid")String pid,
                                                  @PathVariable("newCatalogId")String newCatalogId){
        makeSureUserRights(SecurityUtils.getUser().getUserId());
        journalCustomService.moveCustom(pid,newCatalogId);
        return ResponseEntity.ok().build();
    }
    @ApiOperationSort(16)
    @PostMapping("/updateJournalCatalog")
    @SysLog(operation = "分类修改")
    @ApiOperation(value = "分类修改")
    public ResponseEntity<Void>  updateJournalCatalog(@RequestBody @Valid JournalCatalogParam journalCatalogParam){
        makeSureUserRights(SecurityUtils.getUser().getUserId());
        JournalCatalogUserBO journalCatalogUserBO = new JournalCatalogUserBO();
        journalCatalogUserBO.setCatalogName(journalCatalogParam.getName());
        journalCatalogUserBO.setPid(journalCatalogParam.getPid());
        journalCatalogUserService.updateCatalogUser(journalCatalogUserBO);
        return ResponseEntity.ok().build();
    }

    @ApiOperationSort(19)
    @PostMapping("/updateJournalCustom")
    @SysLog(operation = "站点修改")
    @ApiOperation(value = "站点修改")
    public ResponseEntity<Void>  updateJournalCustom(@RequestBody @Valid JournalParam journalParam){
        makeSureUserRights(SecurityUtils.getUser().getUserId());
        JournalBO journalBO= MapperUtil.nf().map(journalParam, JournalBO.class);
        journalCustomService.updateJournalCustom(journalBO);
        JournalCustomBO byId = journalCustomService.findById(journalParam.getPid());
        AssertUtil.assertThrow("rss解析失败",byId == null);
        journalService.parseJob(byId.getJournalId());
        journalService.refreshES();
        return ResponseEntity.ok().build();
    }


    @ApiOperationSort(20)
    @PostMapping("/addJournalCustom")
    @SysLog(operation = "站点新增")
    @ApiOperation(value = "站点新增")
    public ResponseEntity<Void>  addJournalCustom(@RequestBody @Valid JournalParam journalParam){
        makeSureUserRights(SecurityUtils.getUser().getUserId());
        ArrayList<JournalParam> journalParams = new ArrayList<>();
        journalParam.setPid(SnowFlakeUtil.nextIdStr());
        journalParams.add(journalParam);
        List<JournalBO> journalBOS = MapperUtil.nf().mapAsList(journalParams, JournalBO.class);
        String s= journalCustomService.addJournalCustom(journalBOS);
        if (journalParam.isDoSub()){
            JournalSubQuery journalSubQuery = new JournalSubQuery();
            journalSubQuery.setSub(1);
            journalSubQuery.setRssId(s);
            journalSubQuery.setUserId(SecurityUtils.getUser().getUserId());
            journalService.sub(journalSubQuery);
            journalUserAxisService.addRecord(SecurityUtils.getUser().getUserId(),s);
        }
        JournalCustomBO byId = journalCustomService.findById(s);
        AssertUtil.assertThrow("rss解析失败",byId == null);
        journalService.parseJob(byId.getJournalId());
        journalService.refreshES();
        return ResponseEntity.ok().build();
    }

    @ApiOperationSort(21)
    @DeleteMapping("/deleteById/{pid}")
    @SysLog(operation = "删除站点")
    @ApiOperation(value = "删除站点")
    public ResponseEntity<Void>  deleteById(@PathVariable("pid") String pid){
        makeSureUserRights(SecurityUtils.getUser().getUserId());
        journalCustomService.deleteById(pid);
        journalUserAxisService.deleteByUserIdAndPid(pid,SecurityUtils.getUser().getUserId());
        List<String> byUserAndRssId = journalUserActionService.findByUserAndRssId(pid, SecurityUtils.getUser().getUserId());
        if (CollectionUtil.isNotEmpty(byUserAndRssId)){
            journalUserActionService.deleteBatchByIds(byUserAndRssId);
        }
        return ResponseEntity.ok().build();
    }

    @ApiOperationSort(22)
    @GetMapping("/setAllRead")
    @SysLog(operation = "一键已读")
    @ApiOperation(value = "一键已读")
    public ResponseEntity<Integer>  setAllRead(@RequestParam(required = false) List<String> pids){
        if (CollectionUtil.isNotEmpty(pids)){
            //修改个人站点表数据
            List<JournalCustomBO> byUserAndRssId = journalCustomService.findByIds(pids);
            //清除所有已读数据
            if (CollectionUtil.isNotEmpty(byUserAndRssId)){
                //聚合出公共站点ID
                List<String> collect = byUserAndRssId.stream().map(JournalCustomBO::getJournalId).collect(Collectors.toList());
                journalUserActionService.deleteByUserAndJournalIdS(SecurityUtils.getUserId(), collect);
            }
            byUserAndRssId.forEach(journalCustomBO -> {
                journalCustomBO.setReadTime(new Date());
            });
            journalCustomService.updateBatch(byUserAndRssId);

        }
        return ResponseEntity.ok(0);
    }

    @ApiOperationSort(23)
    @GetMapping("/alreadyRead/{articleId}")
    @SysLog(operation = "文章设置为已读")
    @ApiOperation(value = "文章设置为已读")
    public ResponseEntity<Integer>  alreadyRead(@PathVariable("articleId") String articleId){
        Integer integer = journalUserActionService.changeReadStatus(articleId, SecurityUtils.getUser().getUserId());
        if(integer == null){
            integer =0 ;
        }
        return ResponseEntity.ok(integer);
    }


    @ApiOperationSort(24)
    @PostMapping("/article/save")
    @SysLog(operation = "手动录入")
    @ApiOperation(value = "手动录入")
    public ResponseEntity<Void>  saveArticle(@RequestBody JournalArticleBO journalArticleBO){
        AssertUtil.assertThrow("请传入文件的id", journalArticleBO.getLinkUrl() == null);
        if (journalArticleBO.getTitle() == null || "".equals(journalArticleBO.getTitle())){
            journalArticleBO.setTitle(String.valueOf(System.currentTimeMillis()));
        }
        JournalCustomBO byId = journalCustomService.findById(journalArticleBO.getRssId());
        journalArticleBO.setRssId(byId.getJournalId());
        journalArticleBO.setDigest(journalService.articleDigest(journalArticleBO));
        ArrayList<JournalArticleBO> journalArticleBOArrayList = new ArrayList<>();
        journalArticleBOArrayList.add(journalArticleBO);
        //新增到数据库
        journalArticleService.saveBatch(journalArticleBOArrayList);
        //刷新es
        journalService.refreshES();
        return ResponseEntity.ok().build();
    }

}
